import ProDescriptions from '@ant-design/pro-descriptions';
import type { ProFormInstance } from '@ant-design/pro-form';
import { Card } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel, useRequest } from 'umi';

import UserStatusForm from '@/components/UserStatus';

import UserAuthLogTable from '../User/components/UserAuthLogTable';
import TradeTable from './components/TradeTable';

import * as utils from '@/utils/utils';

import * as api from '@/services/order';
import * as apiUser from '@/services/user';
import { PageContainer } from '@ant-design/pro-components';
import { useMatch } from '@umijs/max';

const OrderDetail: React.FC = (props: any) => {
  // const { match } = props;
  // let orderId = match.params.id;

  const match = useMatch({ path: '/buisness/order/detail/:id' });
  let orderId = match?.params?.id;
  if (!orderId) {
    orderId = '';
  }

  const [current, setCurrent] = useState<API.Order | undefined>(undefined);
  const [premiumUser, setPremiumUser] = useState<API.UserModel | undefined>(
    undefined,
  );
  const formRef = useRef<ProFormInstance>();

  const { getProduct } = useModel('useGlobalModel', (model) => ({
    getProduct: model.getProduct,
  }));

  const { loading } = useRequest(async () => {
    return loadData();
  });

  const loadData = async () => {
    const result = await api.get(orderId);

    console.log('orderDetail.loadData: ', result);

    if (result.success === true && result.data) {
      const product = getProduct(result.data.productId);
      result.data.productName = product?.name;

      setCurrent(result.data);

      if (result.data?.premiumUserId) {
        const userResult = await apiUser.get(result.data.premiumUserId);

        setPremiumUser(userResult.data);
      }
    }

    return Promise.resolve({
      loading: false,
    });
  };

  return (
    <PageContainer>
      {loading && <Card style={{ minHeight: 200 }} loading={loading} />}
      {!loading && (
        <Card>
          <ProDescriptions
            title="订单信息"
            layout="horizontal"
            column={3}
            dataSource={current}
          >
            <ProDescriptions.Item
              label="渠道订单号"
              dataIndex="channelOriginalTradeNo"
            />

            <ProDescriptions.Item label="订单状态" dataIndex="orderStatus" />
            <ProDescriptions.Item
              label="订单编号"
              dataIndex="orderNo"
              renderText={(val, record) => {
                let text = val;
                if (record.productName) {
                  text += ` [${record.productName}]`;
                }
                return text;
              }}
            />
            <ProDescriptions.Item
              label="会员用户"
              dataIndex="premiumUsername"
            />
            <ProDescriptions.Item label="用户名" dataIndex="username" />
            <ProDescriptions.Item
              label="购买方式"
              dataIndex="subscribeType"
              renderText={(val) => {
                return String(val).toUpperCase();
              }}
            />

            <ProDescriptions.Item label="渠道" dataIndex="channel" />
            <ProDescriptions.Item label="渠道商品" dataIndex="channelItemId" />
            {/* <ProDescriptions.Item
              label="渠道订单号"
              dataIndex="channelOriginalTradeNo"
            /> */}
            <ProDescriptions.Item
              label="更新时间"
              dataIndex="updateTime"
              renderText={(val) => {
                return utils.formatUtcToLocal(val);
              }}
            />
          </ProDescriptions>
        </Card>
      )}

      <UserStatusForm
        loading={loading}
        model={premiumUser}
        style={{ marginTop: 20, minHeight: 200 }}
      />
      <TradeTable orderId={orderId} />
      <UserAuthLogTable userId={premiumUser?.id} />
    </PageContainer>
  );
};

export default OrderDetail;
